home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / graphic / jpegsrc4.zip / JQUANT1.C < prev    next >
C/C++ Source or Header  |  1992-07-13  |  23KB  |  593 lines

  1. /*
  2.  * jquant1.c
  3.  *
  4.  * Copyright (C) 1991, 1992, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains 1-pass color quantization (color mapping) routines.
  9.  * These routines are invoked via the methods color_quantize
  10.  * and color_quant_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15. #ifdef QUANT_1PASS_SUPPORTED
  16.  
  17.  
  18. /*
  19.  * The main purpose of 1-pass quantization is to provide a fast, if not very
  20.  * high quality, colormapped output capability.  A 2-pass quantizer usually
  21.  * gives better visual quality; however, for quantized grayscale output this
  22.  * quantizer is perfectly adequate.  Dithering is highly recommended with this
  23.  * quantizer, though you can turn it off if you really want to.
  24.  *
  25.  * This implementation quantizes in the output colorspace.  This has a couple
  26.  * of disadvantages: each pixel must be individually color-converted, and if
  27.  * the color conversion includes gamma correction then quantization is done in
  28.  * a nonlinear space, which is less desirable.  The major advantage is that
  29.  * with the usual output color spaces (RGB, grayscale) an orthogonal grid of
  30.  * representative colors can be used, thus permitting the very simple and fast
  31.  * color lookup scheme used here.  The standard JPEG colorspace (YCbCr) cannot
  32.  * be effectively handled this way, because only about a quarter of an
  33.  * orthogonal grid would fall within the gamut of realizable colors.  Another
  34.  * advantage is that when the user wants quantized grayscale output from a
  35.  * color JPEG file, this quantizer can provide a high-quality result with no
  36.  * special hacking.
  37.  *
  38.  * The gamma-correction problem could be eliminated by adjusting the grid
  39.  * spacing to counteract the gamma correction applied by color_convert.
  40.  * At this writing, gamma correction is not implemented by jdcolor, so
  41.  * nothing is done here.
  42.  *
  43.  * In 1-pass quantization the colormap must be chosen in advance of seeing the
  44.  * image.  We use a map consisting of all combinations of Ncolors[i] color
  45.  * values for the i'th component.  The Ncolors[] values are chosen so that
  46.  * their product, the total number of colors, is no more than that requested.
  47.  * (In most cases, the product will be somewhat less.)
  48.  *
  49.  * Since the colormap is orthogonal, the representative value for each color
  50.  * component can be determined without considering the other components;
  51.  * then these indexes can be combined into a colormap index by a standard
  52.  * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
  53.  * can be precalculated and stored in the lookup table colorindex[].
  54.  * colorindex[i][j] maps pixel value j in component i to the nearest
  55.  * representative value (grid plane) for that component; this index is
  56.  * multiplied by the array stride for component i, so that the
  57.  * index of the colormap entry closest to a given pixel value is just
  58.  *    sum( colorindex[component-number][pixel-component-value] )
  59.  * Aside from being fast, this scheme allows for variable spacing between
  60.  * representative values with no additional lookup cost.
  61.  */
  62.  
  63.  
  64. #define MAX_COMPONENTS 4    /* max components I can handle */
  65.  
  66. static JSAMPARRAY colormap;    /* The actual color map */
  67. /* colormap[i][j] = value of i'th color component for output pixel value j */
  68.  
  69. static JSAMPARRAY colorindex;    /* Precomputed mapping for speed */
  70. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  71.  * premultiplied as described above.  Since colormap indexes must fit into
  72.  * JSAMPLEs, the entries of this array will too.
  73.  */
  74.  
  75. static JSAMPARRAY input_buffer;    /* color conversion workspace */
  76. /* Since our input data is presented in the JPEG colorspace, we have to call
  77.  * color_convert to get it into the output colorspace.  input_buffer is a
  78.  * one-row-high workspace for the result of color_convert.
  79.  */
  80.  
  81.  
  82. /* Declarations for Floyd-Steinberg dithering.
  83.  *
  84.  * Errors are accumulated into the arrays evenrowerrs[] and oddrowerrs[].
  85.  * These have resolutions of 1/16th of a pixel count.  The error at a given
  86.  * pixel is propagated to its unprocessed neighbors using the standard F-S
  87.  * fractions,
  88.  *        ...    (here)    7/16
  89.  *        3/16    5/16    1/16
  90.  * We work left-to-right on even rows, right-to-left on odd rows.
  91.  *
  92.  * In each of the xxxrowerrs[] arrays, indexing is [component#][position].
  93.  * We provide (#columns + 2) entries per component; the extra entry at each
  94.  * end saves us from special-casing the first and last pixels.
  95.  * In evenrowerrs[], the entries for a component are stored left-to-right, but
  96.  * in oddrowerrs[] they are stored right-to-left.  This means we always
  97.  * process the current row's error entries in increasing order and the next
  98.  * row's error entries in decreasing order, regardless of whether we are
  99.  * working L-to-R or R-to-L in the pixel data!
  100.  *
  101.  * Note: on a wide image, we might not have enough room in a PC's near data
  102.  * segment to hold the error arrays; so they are allocated with alloc_medium.
  103.  */
  104.  
  105. #ifdef EIGHT_BIT_SAMPLES
  106. typedef INT16 FSERROR;        /* 16 bits should be enough */
  107. #else
  108. typedef INT32 FSERROR;        /* may need more than 16 bits? */
  109. #endif
  110.  
  111. typedef FSERROR FAR *FSERRPTR;    /* pointer to error array (in FAR storage!) */
  112.  
  113. static FSERRPTR evenrowerrs[MAX_COMPONENTS]; /* errors for even rows */
  114. static FSERRPTR oddrowerrs[MAX_COMPONENTS];  /* errors for odd rows */
  115. static boolean on_odd_row;    /* flag to remember which row we are on */
  116.  
  117.  
  118. /*
  119.  * Policy-making subroutines for color_quant_init: these routines determine
  120.  * the colormap to be used.  The rest of the module only assumes that the
  121.  * colormap is orthogonal.
  122.  *
  123.  *  * select_ncolors decides how to divvy up the available colors
  124.  *    among the components.
  125.  *  * output_value defines the set of representative values for a component.
  126.  *  * largest_input_value defines the mapping from input values to
  127.  *    representative values for a component.
  128.  * Note that the latter two routines may impose different policies for
  129.  * different components, though this is not currently done.
  130.  */
  131.  
  132.  
  133. LOCAL int
  134. select_ncolors (decompress_info_ptr cinfo, int Ncolors[])
  135. /* Determine allocation of desired colors to components, */
  136. /* and fill in Ncolors[] array to indicate choice. */
  137. /* Return value is total number of colors (product of Ncolors[] values). */
  138. {
  139.   int nc = cinfo->color_out_comps; /* number of color components */
  140.   int max_colors = cinfo->desired_number_of_colors;
  141.   int total_colors, iroot, i;
  142.   long temp;
  143.   boolean changed;
  144.  
  145.   /* We can allocate at least the nc'th root of max_colors per component. */
  146.   /* Compute floor(nc'th root of max_colors). */
  147.   iroot = 1;
  148.   do {
  149.     iroot++;
  150.     temp = iroot;        /* set temp = iroot ** nc */
  151.     for (i = 1; i < nc; i++)
  152.       temp *= iroot;
  153.   } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  154.   iroot--;            /* now iroot = floor(root) */
  155.  
  156.   /* Must have at least 2 color values per component */
  157.   if (iroot < 2)
  158.     ERREXIT1(cinfo->emethods, "Cannot quantize to fewer than %d colors",
  159.          (int) temp);
  160.  
  161.   if (cinfo->out_color_space == CS_RGB && nc == 3) {
  162.     /* We provide a special policy for quantizing in RGB space.
  163.      * If 256 colors are requested, we allocate 8 red, 8 green, 4 blue levels;
  164.      * this corresponds to the common 3/3/2-bit scheme.  For other totals,
  165.      * the counts are set so that the number of colors allocated to each
  166.      * component are roughly in the proportion R 3, G 4, B 2.
  167.      * For low color counts, it's easier to hardwire the optimal choices
  168.      * than try to tweak the algorithm to generate them.
  169.      */
  170.     if (max_colors == 256) {
  171.       Ncolors[0] = 8;  Ncolors[1] = 8;  Ncolors[2] = 4;
  172.       return 256;
  173.     }
  174.     if (max_colors < 12) {
  175.       /* Fixed mapping for 8 colors */
  176.       Ncolors[0] = Ncolors[1] = Ncolors[2] = 2;
  177.     } else if (max_colors < 18) {
  178.       /* Fixed mapping for 12 colors */
  179.       Ncolors[0] = 2;  Ncolors[1] = 3;  Ncolors[2] = 2;
  180.     } else if (max_colors < 24) {
  181.       /* Fixed mapping for 18 colors */
  182.